<template>


	<uni-card v-if="mydev">
		<!-- 这里显示连接过的设备 -->

		<view class="history_title">配对连接设备</view>

		<view v-for="item in devlist" :key="item" class="history_box">
			<view>ID:{{item.address}}</view>
			<view>NAME:{{item.name}}</view>
			<view v-show="isconnect" class="r_connect" @click="againcreateBluetoothConnect(item)">连接断开，重新连接</view>
		</view>
	</uni-card>
	<uni-card v-else>
		<view>无设备</view>
	</uni-card>


	<view class="btn-box">
		<button class="mini-btn" type="primary" @tap="devicesDiscovery" :disabled="issearching">蓝牙搜索</button>
		<button class="mini-btn" type="primary" @tap="breakBT" :disabled="issearching">关闭连接</button>
		<button class="mini-btn" type="primary" @tap="closeBt" :disabled="issearching">关闭蓝牙</button>

	</view>

	<uni-card title="搜索设备列表" :sub-title="subTitle" :thumbnail="avatar">

		<view v-for="item in discovreylist" :key="item" class="discovery" @click="createBluetoothConnect(item)">
			<image src="../../static/bluetoothing.png" class="bluetooth-image"></image>
			<view class="discovery-id">ID:{{ item.address }}</view>
			<view class="discovery-name">NAME:{{ item.name }}</view>
		</view>



	</uni-card>

	<view class="isshowlog" @dblclick="showlog"></view>
	<view class="footer" v-show="isshow">{{connect_info}}</view>


</template>

<script>
	const bt = uni.requireNativePlugin('Common-BT');

	import sqlite from "@/common/sqlite.js"


	export default {
		data() {
			return {
				isdiscovery: false, // 是否在搜索中
				avatar: "/static/search.png", //搜索的图标。默认灰色
				subTitle: "", // 搜索的状态
				mydev: false, // 历史连接设备显示
				discovreylist: [], //搜索的蓝牙列表
				isconnect: true, //是否显示断开重连
				connect_info: "", //蓝牙返回的数据
				issearching: false, //是否在搜索
				devlist: [], // 历史连接过的蓝牙
				addprv: "", //当前连接的蓝牙
				isshow: false ,// 是否显示 最下面那行日志
		 
			}
		},
		mounted() {

			//这里用来测试跟新实时图是否正常

			// this.timer = setInterval(() => {
			// 	// 业务逻辑	
			// 	this.$store.commit("setheart", 78 + Math.random() * 30)
			// 	console.log("这里收到数据", this.$store.state.heart)
			// }, 2000)
			sqlite.selectBluetooth().then(res => {
				console.log(res)
				if (res.length > 0) {
					this.mydev = true
					this.devlist = res
				}

			}, function(res) {
				console.log(res)
			})




			bt.hasPermission(result => {
				//result数据：{"status":true} 如果没有权限程序会自动申请权限
				const msg = JSON.stringify(result);
				if (!result.status) {
					uni.showToast({
						title: "无蓝牙权限",
						icon: "error",
						duration: 2000
					})
				}
			});

			bt.isSupport(result => {
				//result数据：{"status":true} 
				const msg = JSON.stringify(result);
				console.log('是否支持蓝牙：' + result.status)
			});

			//打开蓝牙
			bt.openBT(result => {
				//result数据：{"status":true} 
				const msg = JSON.stringify(result);
				console.log('开启蓝牙是否成功：' + result.status)
			});




		},
		methods: {

			//切换显示蓝牙返回的数据
			showlog() {
				console.log("蓝牙连接")
				this.isshow = !this.isshow

			},


			//开始搜索设备
			devicesDiscovery() {

				if (this.isdiscovery) {
					return
				}
				console.log("开启搜索")
				this.issearching = true


				setTimeout(() => {
					this.issearching = false
					this.subTitle = ""
					this.isdiscovery = false
					this.avatar = "/static/search.png" //开始搜索替换图片
				}, 40 * 1000)


				this.discovreylist = []
				this.avatar = "/static/searching.png" //开始搜索替换图片
				this.subTitle = "搜索中..."
				this.isdiscovery = true
				bt.listBT(result => {
					console.log(result)
					if (result.list) {
						let blu_list = JSON.parse(result.list)
						this.discovreylist = blu_list
					}

					if (result.code == 0) {
						this.subTitle = "开始搜索..."
					} else if (result.code == 2) {
						this.subTitle = "搜索中..."
					} else if (result.code == 1) {}

				});

			},




			//停止蓝牙设备搜索
			stopDiscovery() {

				this.issearching = false
				this.subTitle = ""
				this.isdiscovery = false
				this.avatar = "/static/search.png" //开始搜索替换图片
				bt.stopSearch(res => {
					console.log("停止搜索", res)
				})
			},

			//点重连
			againcreateBluetoothConnect(item) {
				this.createBluetoothConnect(item)
			},

			//连接蓝牙,点击搜索到的蓝牙时进行连接
			createBluetoothConnect(item) {


				this.stopDiscovery()

				console.log("进行蓝牙连接")
				let this_ = this
				//  判断是否配对
				let address = item.address
				if (item.status == "未配对") {

					bt.pairBT({
						"btAddress": address
					}, result => {
						//result数据：{"code":100,"msg":"配对完成，请刷新列表"} 
						const msg = JSON.stringify(result);
						console.log('配对结果：' + msg)
						if (result.code == 100) {
							this.connect(address, item) //配对成功之后连接
						}

					});
				} else {
					this.connect(address, item)
				}


			},
			//将连接的蓝牙信息保存下来
			saveBluInfo(address, item) {
				this.mydev = true
				let this_ = this
				sqlite.selectBlu(address).then(function(res) {

					if (res.length <= 0) {
						console.log(this_.addprv != address, "这里？？？")
						if (this_.addprv != address) {
							this_.addprv = address
							//连接成功的设备保存到缓存
							this_.mydev = true
							this_.devlist.push(item)
							//历史连接保存
							sqlite.addRowBluetooth(address, item.name).then(function(res) {
								console.log("这里保存", JSON.stringify(res))
							}, function(res) {
								console.log("报错", JSON.stringify(res))
							})
						}

					}
				})

			},
			closeBt() {
				bt.closeBT(result => {
					console.log('蓝牙是否关闭：', result)
				});
			},


			//连接方法， 
			connect(address, item) {
				bt.connectBT({
					"btAddress": address
				}, result => {
					//result数据：{"code":200,"msg":"连接成功"}

					this.connect_info = JSON.stringify(result)
					console.log(result)
					if (result.code == 200) {
						this.saveBluInfo(address, item)
						this.parse_data(result)
					} 
					if (result.code == 200 &&   result.msg && result.msg.indexOf("请勿重复连接")!=-1) {
						//提示重连连接怎断开，进行重新连接
						this.breakBT().then( res => {
								console.log("蓝牙已断开重新连接")
								this.connect(address, item)
							},
						)
						
					} 
					if(result.code == 200 && result.msg && result.msg.indexOf("设备已连接")!=-1){
						uni.showToast({
							title:"蓝牙已连接",
							icon:"success",
							duration:2000
						})
					}
					if(result.code != 200) {
						this.isconnect = true
						uni.showToast({
							title: "蓝牙已断开连接",
							icon: "error",
							duration: 2000,
						})

					}

				});
			},

			//处理蓝牙返回的结果数据
			parse_data(result) {
				this.isconnect = false
				 

				// console.log(result)
				try {


					let heartjson = result.value
					// console.log("heartjson", heartjson)
					let heart_dict = JSON.parse(heartjson)
					// console.log("心跳对象", heart_dict)
					let heart = heart_dict.heart
					// console.log("心跳值", heart)
					this.$store.commit("setheart", heart + Math.random()) //加个随机数避免，心跳不变，数据不更新
				} catch (e) {
					//TODO handle the exception
					//有一种状态就是 端口后提示请勿重连，可以主动断开进行连接

					console.log(e)



				}
			},

			//蓝牙状态
			bluetoothStatus() {
				bt.connectStatus(result => {
					//接收
					const content = JSON.stringify(result);
					console.log("蓝牙连接状态", content)
				});
			},

			//断开连接
			breakBT() {
				return new Promise((resolve, reject) => {
					bt.breakBT(result => {
						//result数据：{"code":100,"msg":"连接成功"}
						const msg = JSON.stringify(result);
						console.log(msg);
						this.isconnect = true
						resolve(true)
					});
				})
			}

		}
	}
</script>

<style scoped>
	.btn-box {
		text-align: center;
	}

	.btn-box button {
		margin-left: 10px;
		width: 60%;
		display: inline-block;
	}

	.discovery {
		color: black;
		margin-top: 20px;
		background-color: #e5e5e5;
		border-radius: 3px;
		position: relative;
		height: 60px;
	}



	.bluetooth-image {
		width: 30px;
		height: 30px;
		display: flex;
		position: absolute;
		top: 15px;

	}

	.discovery .discovery-id {
		display: inline-block;
		position: absolute;
		top: 10px;
		left: 15%;
	}

	.discovery:active {
		background-color: #f9f9f9;
	}


	.discovery .discovery-name {
		display: inline-block;
		position: absolute;
		top: 30px;
		left: 15%;
	}

	.footer {
		margin-top: 20px;
		height: 10px;
		text-align: center;
		padding-bottom: 20px;
	}

	.r_connect {
		margin-right: 20px;
		color: #0055ff;
		margin-top: 10px;
	}

	.history_box {
		background-color: #f7f7f7;
		margin: 5px 0 5px 0;
	}

	.history_box view {
		margin: 5px 0 5px 10px;
	}

	.history_title {
		font-size: 18px;
		font-weight: 600;
		margin-bottom: 10px;
	}

	.isshowlog {
		padding: 30px;
		background-color: #ffffff;
	}
</style>
